package com.byx.chatserver.service.impl;

import com.byx.chatserver.dto.*;
import com.byx.chatserver.entity.Group;
import com.byx.chatserver.entity.User;
import com.byx.chatserver.mapper.IUserActionMapper;
import com.byx.chatserver.service.IUserActionService;
import com.byx.imserverutil.entity.ImMessage;
import com.byx.imserverutil.entity.MessageContentType;
import com.byx.imserverutil.entity.MessageType;
import com.byx.imserverutil.factory.ImServiceFactory;
import com.byx.imserverutil.netty.GroupInterface;
import com.byx.imserverutil.netty.NettyWebSocketImServiceImpl;
import com.byx.springboot.unifiedresponseresult.entity.ResultCode;
import com.byx.springboot.unifiedresponseresult.entity.ServerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * UserActionServiceImpl
 *
 * @author Superb
 * @date 2021/4/20 20:57
 */
@Slf4j
@Service
public class UserActionServiceImpl implements IUserActionService, GroupInterface {
    private final NettyWebSocketImServiceImpl imService;
    private IUserActionMapper userActionMapper;

    public static final int USER_OWNER = 0;
    public static final int USER_MANAGER = 1;
    public static final int USER_NORMAL = 2;

    public UserActionServiceImpl() {
        imService = (NettyWebSocketImServiceImpl) ImServiceFactory.getImService();
        imService.setGroupInterface(this);
    }

    @Autowired
    public void setUserActionMapper(IUserActionMapper userActionMapper) {
        this.userActionMapper = userActionMapper;
    }


    /**
     * 通过用户id获取用户详细信息
     *
     * @param id id
     * @return 用户
     */
    @Override
    public User getUserInfoById(Long id) {
        return userActionMapper.getUserInfoById(id);
    }

    /**
     * 通过用户账号获取用户详细信息
     *
     * @param loginId 账号
     * @return 用户
     */
    @Override
    public User getUserInfoByLoginId(String loginId) {
        return userActionMapper.getUserInfoByLoginId(loginId);
    }

    @Override
    public List<SimpleUserDto> fuzzySearchUser(String searchKey, boolean isLimited) {
        try {
            return isLimited ? userActionMapper.fuzzySearchUserLimited(searchKey) : userActionMapper.fuzzySearchUser(searchKey);
        }catch (Exception e){
            e.printStackTrace();
            throw new ServerException(ResultCode.INTERNAL_SERVER_ERROR);
        }
    }

    @Override
    public List<SimpleGroupDto> fuzzySearchGroup(String searchKey, boolean isLimited) {
        try {
            return isLimited ? userActionMapper.fuzzySearchGroupLimited(searchKey) : userActionMapper.fuzzySearchGroup(searchKey);
        }catch (Exception e){
            throw new ServerException(ResultCode.INTERNAL_SERVER_ERROR);
        }
    }

    @Override
    public void createGroup(Group group) {
        try {
            userActionMapper.insertGroup(group);
            requestJoinGroupWithNoResp(group.getOwnerId(),group.getId(),userActionMapper.queryUserSimpleInfoById(group.getOwnerId()).getNickName());
            userActionMapper.insertGroupUsers(group);
        }catch (Exception e){
            log.error("createGroup:",e);
            throw new ServerException(ResultCode.FAILED);
        }
    }

    /**
     * 加入指定群聊
     *
     * @param groupId
     */
    @Override
    public void requestJoinGroup(String sender,Integer groupId,String remark) {
        // 2021/4/20 申请指定群聊 需要用聊天服务向群主发一条验证消息
        String ownerId = userActionMapper.queryOwnerIdByGroupId(groupId);
        ImMessage imMessage = ImMessage.newBuilder()
                .setSenderId(sender)
                .setRecipientId(ownerId)
                .setType(MessageType.VERIFICATION_MSG)
                .setContentType(MessageContentType.TEXT)
                .setContent(remark)
                .setTimestamp(System.currentTimeMillis())
                .build();
        imService.sendMessage(imMessage.convert());
    }

    /**
     * 响应加群请求，群主操作
     *
     * @param applicantId
     */
    @Override
    public void responseJoinGroup(String applicantId,boolean agree) {
        // TODO: 2021/4/21 对加群请求作出响应
        ImMessage.Builder builder = ImMessage.newBuilder();
        if (agree){
            builder.setContent("您已加入该群");
        }else {
            builder.setContent("管理员拒绝了您的加群申请，请联系群主或者管理员");
        }
        ImMessage imMessage = builder.setRecipientId(applicantId)
                .setType(MessageType.SYSTEM_MSG)
                .setContentType(MessageContentType.TEXT)
                .setTimestamp(System.currentTimeMillis())
                .build();
        imService.sendMessage(imMessage.convert());
    }

    @Override
    public void requestJoinGroupWithNoResp(Long userId, Long groupId, String remark) {
        User user = new User();
        user.setId(userId);
        user.setNickName(remark);
        userActionMapper.insertGroupUser(groupId,user,USER_OWNER);
    }

    @Override
    public List<FriendGroupDto> getUserFriendGroup(Long id) {
        return userActionMapper.getUserFriendGroup(id);
    }

    @Override
    public Integer addFriendGroup(FriendGroupDto groupDto) {
        userActionMapper.insertFriendGroup(groupDto);
        return groupDto.getGroupId();
    }

    @Override
    public User queryUserSimpleInfoById(Long id) {
        return userActionMapper.queryUserSimpleInfoById(id);
    }

    @Override
    public Map<Integer,List<SimpleGroupDto>> queryUserGroupById(Long id) {
        Map<Integer,List<SimpleGroupDto>> groupDtoMap = new HashMap<>(3);
        List<GroupRole> group = userActionMapper.queryUserGroup(id);
        for (GroupRole groupRole : group){
            SimpleGroupDto groupDto = new SimpleGroupDto();
            groupDto.setId(groupRole.getId());
            groupDto.setName(groupRole.getName());
            groupDto.setAvatar(groupRole.getAvatar());
            if (!groupDtoMap.containsKey(groupRole.getRole())){
                groupDtoMap.put(groupRole.getRole(), new ArrayList<>());
            }
            groupDtoMap.get(groupRole.getRole()).add(groupDto);
        }
        return groupDtoMap;
    }

    @Override
    public GroupDto queryUserGroupDetail(Long userId, Long groupId) {
        return userActionMapper.queryUserGroupDetailById(userId,groupId);
    }

    @Override
    public void changeUserInfo(User user) {
        userActionMapper.changeUserInfo(user);
    }

    @Override
    public void changeUserAvatar(String loginId, String avatar, Long timestamp) {
        userActionMapper.changeUserAvatar(loginId, avatar, timestamp);
    }

    @Override
    public List<String> queryMembersInGroup(Integer groupId) {
        return userActionMapper.queryGroupMembersLoginId(groupId);
    }
}
